package com.hxd.buybooksystem.ui.fragment

import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.QueryListener
import com.hjq.image.ImageLoader
import com.hxd.buybooksystem.R
import com.hxd.buybooksystem.base.common.MyLazyFragment
import com.hxd.buybooksystem.bean.UserInfo
import com.hxd.buybooksystem.ui.activity.HistoryOrderActivity
import com.hxd.buybooksystem.ui.activity.MainActivity
import com.hxd.buybooksystem.ui.activity.UserInfoActivity
import com.hxd.buybooksystem.uitls.L
import com.vondear.rxtool.RxSPTool
import kotlinx.android.synthetic.main.activity_user_info.*
import kotlinx.android.synthetic.main.fragment_user.*
import org.jetbrains.anko.support.v4.startActivity

/**
 *  项目名：    BuyBookSystem
 *  包名：      com.hxd.buybooksystem.ui.fragment
 *  文件名:     IndexFragment
 *  创建者:     HXD
 *  创建时间:   2019/5/28 20:19
 *  描述:       个人中心页面
 */

class UserFragment : MyLazyFragment<MainActivity>() {

    private val objectId: String? by lazy { RxSPTool.getString(activity, "objectId") }

    //设置单例静态方法
    companion object {
        fun newInstance(): UserFragment {
            return UserFragment()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_user
    }

    override fun getTitleBarId(): Int {
        return 0
    }

    override fun initView() {
        sb_userInfo_mine.setOnClickListener {
            startActivity<UserInfoActivity>()
            finish()
        }

        sb_historyOrder_mine.setOnClickListener {
            startActivity<HistoryOrderActivity>()
        }
    }

    override fun initData() {
        loadUserInfo()
    }

    /**
     * 载入用户信息
     */
    private fun loadUserInfo() {
        val bmobQuery = BmobQuery<UserInfo>()
        bmobQuery.getObject(objectId, object : QueryListener<UserInfo>() {
            override fun done(userInfo: UserInfo, e: BmobException?) {
                if (e == null) {
                    L.i("查询成功, $userInfo")
                    tv_name_mine.text = userInfo.name
                    if (userInfo.image != null){
                        ImageLoader.loadCircleImage(iv_photo_mine,userInfo.image)
                    }
                } else {
                    L.i("查询失败：" + e.errorCode)
                }
            }
        })
    }

    override fun onRestart() {
        super.onRestart()
        loadUserInfo()
    }
}